package com.colin.action;

import com.colin.database.MysqlDataSource;
import com.colin.ui.component.ChooseFrame;
import com.colin.util.GenUtil;
import com.colin.util.NotificationUtil;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.ProjectManager;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.io.FileReader;
import java.sql.SQLException;
import java.util.List;

import static com.colin.database.Config.FILE_STORAGE_FILE_ROOT_PATH;

public class SearchTableAction extends AnAction {

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        if (e.getProject() == null) {
            return;
        }
        ChooseFrame chooseFrame = new ChooseFrame(queryTables(), queryModule());
        int confirmDialog = JOptionPane.showConfirmDialog(null, chooseFrame, "选择表", JOptionPane.YES_NO_CANCEL_OPTION);
        if (confirmDialog == JOptionPane.OK_OPTION) {
            if (chooseFrame.getSelectedTabels() != null && !chooseFrame.getSelectedTabels().isEmpty()) {
                // 执行确认后的操作，这里示例为显示选择的值
                try {
                    GenUtil.gen(chooseFrame.getSelectedTabels(), chooseFrame.getAuthor(), chooseFrame.getModule());
                    NotificationUtil.error(chooseFrame.getSelectedTabels() + " ,生成成功");
                } catch (Exception ex) {
                    NotificationUtil.error("生成失败, msg = " + ex.getMessage());
                }
            }
        }
    }

    private String[] queryTables() {
        // 创建下拉框的选项
        return MysqlDataSource.executeSQL("show tables", String.class, (resultSet) -> {
            try {
                return resultSet.getString("Tables_in_icms");
            } catch (SQLException ex) {
                return "UNKONWN";
            }
        }).toArray(String[]::new);
    }

    private String[] queryModule() {
        // 获取项目模块名称
        MavenXpp3Reader reader = new MavenXpp3Reader();
        try {
            Model model = reader.read(new FileReader(FILE_STORAGE_FILE_ROOT_PATH + "/pom.xml"));
            List<String> modules = model.getModules();
            return modules.stream().filter(e -> e.contains("-basic")).map(e -> {
                if (e.contains("/")) {
                    return e.substring(e.lastIndexOf("/") + 1);
                }
                return e;
            }).toArray(String[]::new);
        } catch (Exception ex) {
            return new String[0];
        }
    }
}
